﻿using FieldTools.Client.Command;
using FieldTools.Client.View;
using FieldTools.Client.View.Window;
using FieldTools.Client.ViewModel;
using FieldTools.Client.ViewModel.Window;
using FieldTools.Client.Entity;
using FieldTools.Util;
using HandyControl.Controls;
using HandyControl.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MessageBox = HandyControl.Controls.MessageBox;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using MahApps.Metro.Controls.Dialogs;
using FieldTools.Util.Helper;
using ControlzEx.Theming;
using FieldTools.Client.View.Control;

namespace FieldTools.Client
{
    /// <summary>
    /// ToolsBox.xaml 的交互逻辑，这里可以分离，但为了保留一些痕迹，我混合了事件模型与数据模型来写，成熟的项目大可不必如此，请使用MVVM解耦合，发挥WPF的美丽
    /// </summary>
    public partial class ToolsBox : MetroWindow, ITransientDependency
    {
        /// <summary>
        /// 
        /// </summary>
        public ToolsBox(ToolsBoxViewModel vm)
        {
            InitializeComponent();
            Init();
            this.DataContext = vm;
            //载入所有文件缓存供后续调用
            CacheHelper.GetFileCacheAll();
            
            //创建控制台并关闭，以确保控制台资源得到初始化，且不弹出额外的窗口
            //consoleWindow = new ConsoleWindow();
            //consoleWindow.Close();
            //consoleWindow = null;

            this.Closing += (s, e) =>
            {
                consoleWindow?.Close();
            };

            //ThemeManager.Current.ChangeTheme(this, "Dark.Green");
        }
        #region 数据实体/通知属性
        ///// <summary>
        ///// 客户端配置文件实体
        ///// </summary>
        //public ClientConfig ClientConfig
        //{
        //    get { return (ClientConfig)GetValue(ClientConfigProperty); }
        //    set { SetValue(ClientConfigProperty, value); }
        //}
        ///// <summary>
        ///// 客户端配置文件实体依赖属性
        ///// </summary>
        //public static readonly DependencyProperty ClientConfigProperty = DependencyProperty.Register("ClientConfig", typeof(ClientConfig), typeof(ToolsBox), null);

        /// <summary>
        /// 底部通知消息
        /// </summary>
        public string NoticeMsg
        {
            get { return (string)GetValue(NoticeMsgProperty); }
            set { SetValue(NoticeMsgProperty, value); }
        }
        /// <summary>
        /// 底部通知消息依赖属性
        /// </summary>
        public static readonly DependencyProperty NoticeMsgProperty = DependencyProperty.Register("NoticeMsg", typeof(string), typeof(ToolsBox), null);


        /// <summary>
        /// 菜单界面数据
        /// </summary>
        public List<MutViewControl> MutViewControls
        {
            get { return (List<MutViewControl>)GetValue(MutViewControlsProperty); }
            set { SetValue(MutViewControlsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MutViewControls.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MutViewControlsProperty =
            DependencyProperty.Register("MutViewControls", typeof(List<MutViewControl>), typeof(ToolsBox), null);


        /// <summary>
        /// 设置窗口
        /// </summary>
        System.Windows.Window? settingWindow { get; set; }
        /// <summary>
        /// 判断双击事件的计数,容器控件没有双击数据的无赖之举
        /// </summary>
        private long lastTitleLeftDownTime = 0;
        #endregion

        #region 数据初始化
        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            NoticeMsg = "欢迎使用FieldTools，祝您愉快，当前模式：<" + GlobalParm.LoginType switch { 1 => "在线模式", 2 => "离线模式", _ => "未知" } + ">";
            //SetClientConfig();
            SetCardMenu();
        }
        /// <summary>
        /// 设置卡片菜单
        /// </summary>
        private void SetCardMenu()
        {
            WindowManager.Register<TextDialogWindow>("TextDialogWindow");
            WindowManager.Register<BlankWindow>("BlankWindow");
            WindowManager.Register<HttpClientWindow>("HttpClientWindow");
            WindowManager.Register<HttpServerWindow>("HttpServerWindow");
            WindowManager.Register<JSInterpreterWindow>("JSInterpreterWindow");
            WindowManager.Register<MyQQWindow>("MyQQWindow");
            WindowManager.Register<PersonWindow>("PersonWindow");
            WindowManager.Register<WebViewWindow>("WebViewWindow");
            WindowManager.Register<TCPClientWindow>("TCPClientWindow");
            WindowManager.Register<TCPServerWindow>("TCPServerWindow");
            WindowManager.Register<IdentityCardWindow>("IdentityCardWindow");
            WindowManager.Register<XMLWindow>("XMLWindow");
            WindowManager.Register<CacheWindow>("CacheWindow");
            WindowManager.Register<ProcessWindow>("ProcessWindow");
            WindowManager.Register<MihoyoWindow>("MihoyoWindow");
            WindowManager.Register<RegexWindow>("RegexWindow");
            WindowManager.Register<PicsShowWindow>("PicsShowWindow");
            WindowManager.Register<WeChatWindow>("WeChatWindow");
            WindowManager.Register<ADBWindow>("ADBWindow");

            var sa = System.IO.Directory.GetCurrentDirectory();
            //基础工具
            object m2 = new { 
                Title = "工具集合",
                StateContent = "暂时大乱炖，后续再分",
                //ThemeColor = ClientConfig.ThemeColor,
                MutControls = new List<ControlCon>() {
                    //new ControlCon()
                    //{
                    //    Title = "TCP服务端",
                    //    Name = "TCPServerControl",
                    //    ImgPath = $"{sa}/Resource/testpic3.png",
                    //    Remark = "一个简单的TCP请求测试工具（服务端），基于RRQMSocket项目（作者：若汝棋茗）"
                    //},new ControlCon()
                    //{
                    //    Title = "TCP客户端",
                    //    Name = "TCPClientControl",
                    //    ImgPath = $"{sa}/Resource/testpic3.png",
                    //    Remark = "一个简单的TCP请求测试工具（客户端），基于RRQMSocket项目（作者：若汝棋茗）"
                    //},
                    //new ControlCon()
                    //{
                    //    Title = "HTTP客户端",
                    //    Name = "HttpClientControl",
                    //    ImgPath = $"{sa}/Resource/testpic3.png",
                    //    Remark = "一个简单的HTTP请求测试工具（客户端）"
                    //},
                    new()
                    {
                        Title = "HTTP服务端",
                        Name = "HttpServerWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "内置http服务端"
                    },
                    new()
                    {
                        Title = "JS解释器",
                        Name = "JSInterpreterWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "基于Jering.Javascript.NodeJS 项目（作者：JeremyTCD）开发的JS语句执行器，可以直接执行JS脚本语句和JS脚本文件"
                    },
                    new()
                    {
                        Title = "内置浏览器",
                        Name = "WebViewWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "微软官方WebView2库，Edge (Chromium)浏览器内核"
                    },
                    new()
                    {
                        Title = "身份证工具",
                        Name = "IdentityCardWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "身份证工具"
                    },
                    new()
                    {
                        Title = "xml工具",
                        Name = "XMLWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "xml工具，提取xpath"
                    },
                    new()
                    {
                        Title = "缓存工具",
                        Name = "CacheWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "缓存工具"
                    },
                    new()
                    {
                        Title = "进程工具",
                        Name = "ProcessWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "当前进程工具"
                    },
                    new()
                    {
                        Title = "正则工具",
                        Name = "RegexWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "正则测试工具"
                    },
                    new()
                    {
                        Title = "网络图片浏览器",
                        Name = "PicsShowWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "快捷浏览多张网络图片"
                    },
                    new()
                    {
                        Title = "ADB工具",
                        Name = "ADBWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "安卓手机的adb调试工具，支持无线连接"
                    },
                    new()
                    {
                        Title = "空白页面",
                        Name = "BlankWindow",
                        ImgPath = $"{sa}/Resource/testpic3.png",
                        Remark = "着姿势一个用来测试的空白玩意🙂🙂"
                    }
                }
            };
            M2.DataContext = m2;

            object m3 = new
            {
                Title = "数据对接类工具",
                StateContent = "这些工具通常是定制开发出来用于对接指定软件数据的，可以简单理解为第三方操作端",
                MutControls = new List<ControlCon>() {
                    new()
                    {
                        Title = "QQ Robot框架",
                        Name = "MyQQWindow",
                        ImgPath = $"{sa}/Resource/testpic1.png",
                        Remark = "QQ机器人简易对接客户端（onebot协议），支持自定义回复、预定义接口调用、自定义JS脚本等功能"
                    },
                    new()
                    {
                        Title = "米游社工具",
                        Name = "MihoyoWindow",
                        ImgPath = $"{sa}/Resource/testpic1.png",
                        Remark = "米哈游官方论坛米游社的资源爬取工具"
                    },
                    new()
                    {
                        Title = "微信工具",
                        Name = "WeChatWindow",
                        ImgPath = $"{sa}/Resource/testpic1.png",
                        Remark = "微信相关工具"
                    },
                }
            };
            M3.DataContext = m3;
        }
        /// <summary>
        /// 设置配置文件
        /// </summary>
        private void SetClientConfig()
        {
            string jsonString = JsonExtention.GetAppsettingJson("ClientConfig.json") ?? "";//读取配置文件
            //ClientConfig = jsonString.ToObject<ClientConfig>();
        }
        #endregion

        #region 事件
        private void HamburgerMenuControl_OnItemInvoked(object sender, HamburgerMenuItemInvokedEventArgs e)
        {
            HamburgerMenuControl.Content = e.InvokedItem;
        }
        private void LaunchGitHubSite(object sender, RoutedEventArgs e)
        {
            // Launch the GitHub site...
            //System.Diagnostics.Process.Start("https://gitee.com/fieldtianye/field-tools"); 
            //从注册表中读取默认浏览器可执行文件路径
            RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"http\shell\open\command\");
            string s = key.GetValue("").ToString();
            //s就是你的默认浏览器，不过后面带了参数，把它截去，不过需要注意的是：不同的浏览器后面的参数不一样！
            //"D:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -- "%1"
            Regex r = new(@"(C:)(.+?)(exe)");
            var pro = r.Match(s);
            if (pro.Success)
            {
                System.Diagnostics.Process.Start(pro.Value, "https://gitee.com/fieldtianye/field-tools");
            }
        }

        private void DeployCupCakes(object sender, RoutedEventArgs e)
        {
            // deploy some CupCakes...
            //SettingFrom();
        }
        /// <summary>
        /// 设置窗口置顶
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetTopmost_Click(object sender, RoutedEventArgs e)
        {
            Topmost = !Topmost;
            if (Topmost == true)
            {
                Growl.Success(new GrowlInfo()
                {
                    Message = "窗口已置顶",
                    Type = InfoType.Success,
                    WaitTime = 1,
                    ShowDateTime = false,
                    FlowDirection = FlowDirection.RightToLeft,
                });
                topMostIcon.Foreground = Brushes.Coral;
            }
            else
            {
                Growl.Success(new GrowlInfo()
                {
                    Message = "窗口已取消置顶",
                    Type = InfoType.Success,
                    WaitTime = 1,
                    ShowDateTime = false,
                    FlowDirection = FlowDirection.RightToLeft,
                });
                topMostIcon.Foreground = Brushes.White;
            }
        }
        /// <summary>
        /// 设置窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SettingFrom_Click(object sender, RoutedEventArgs e)
        {
            //SettingFrom();
        }
        /// <summary>
        /// 窗口关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Close_Click(object sender, RoutedEventArgs e)
        {
            var res = MessageBox.Show("是否关闭当前窗口", button: MessageBoxButton.YesNo, icon: MessageBoxImage.Question);
            if (res == MessageBoxResult.Yes)
            {
                this.Close();
                //保存配置文件todo
            }
        }
        /// <summary>
        /// 窗口放大
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Max_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == System.Windows.WindowState.Maximized)
            {
                this.WindowState = System.Windows.WindowState.Normal;
            }
            else
            {
                this.WindowState = System.Windows.WindowState.Maximized;
            }
        }
        /// <summary>
        /// 最小化窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Min_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Minimized;
        }
        /// <summary>
        /// 拖动窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Move_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }
        /// <summary>
        /// 双击最大化或还原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Zoom_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

            long ticks = DateTime.Now.Ticks / 1000;
            if (ticks - 2000 > lastTitleLeftDownTime)
            {
                lastTitleLeftDownTime = ticks;
            }
            else
            {
                lastTitleLeftDownTime = 0;
                Max_Click(null, null);
            }
        }
        #endregion

        #region 业务方法
        /// <summary>
        /// 打开或关闭设置窗口
        /// </summary>
        private void SettingFrom()
        {
            //if (settingWindow == null)
            //{
            //    SettingViewModel settingViewModel = new SettingViewModel() { CallbackMethod = SetThemeColor };
            //    settingWindow = WindowManager.Show("SettingWindow", settingViewModel);
            //}
            //else
            //{
            //    //通过反射判断窗口是否关闭
            //    var propertyInfo = typeof(Window).GetProperty("IsDisposed", BindingFlags.NonPublic | BindingFlags.Instance);
            //    var isDisposed = (bool)propertyInfo.GetValue(settingWindow);
            //    if (isDisposed)
            //    {
            //        SettingViewModel settingViewModel = new SettingViewModel() { CallbackMethod = SetThemeColor };
            //        settingWindow = WindowManager.Show("SettingWindow", settingViewModel);
            //    }
            //    else
            //    {
            //        settingWindow.Close();
            //        settingWindow = null;
            //    }
            //}
        }
        /// <summary>
        /// 设置主题色，暂时仅主题色，后续扩展
        /// </summary>
        /// <param name="themeColor"></param>
        private void SetThemeColor(string themeColor)
        {
            //ClientConfig.ThemeColor.MainColor = themeColor;
        }
        #endregion

        ConsoleWindow? consoleWindow = null;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //ConsoleManager.Toggle();

            if (consoleWindow == null)
            {
                consoleWindow = new ConsoleWindow();
                consoleWindow.Show();
            }
            else
            {
                consoleWindow.Close();
                consoleWindow = null;
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //JSInterpreterWindow window = new();
            //window.Show();
            //TestWindow testWindow = new();
            //testWindow.Show();
            
            Console.WriteLine("测试控制台打印");
            //刷新console
            Kernel32Helper.FlushConsoleInputBuffer();
        }
    }
}
